import { createDayHours } from './utils.js'

let timeline;
const scrollMap = [];
export const $pointer = $('<div class="time-pointer"><div class="time-arrow"></div></div>');
export const $desc = $('<div class="datetime-description">00:00:00</div>');
const timeAxisTemplate = (width) => $(`
      <div class="time-axis">
        <div class="time-scroller" style="width: ${width}px;"></div>
        <div class="time-timeline" style="width: ${width}px;"></div>
      </div>
    `)

export default class Timeline {
    #width;
    $container;
    $timeAxis;

    static getInstance () {
        return timeline || (timeline =  new Timeline());
    }

    init (width) {
        const $timeAxis = timeAxisTemplate(width);
        const $scroller = $timeAxis.find('.time-scroller');

        this.#width = width;
        this.$timeAxis = $timeAxis;
        this.renderTimeline();

        if (!$scroller.children().has($pointer).length) {
            $scroller.append($pointer);
            $scroller.append($desc);
        }


        return this.$timeAxis
    }

    initMinuteSize (width) {
        let minutes = 0
        while (width > 0) {
            minutes +=1
            width -= 200
        }
        return minutes;
    }

    renderMinutes (size, hour, half, minute) {
        const __ten = minute ? `<span class="timeline-minute-text">${'10'}</span>` : ''
        const __twenty = minute ? `<span class="timeline-minute-text">${'20'}</span>` : ''
        const __hourHalf = half ? `<span class="timeline-hour-half-text">${hour + ':30'}</span>` : ''
        const __forty = minute ? `<span class="timeline-minute-text">${'40'}</span>` : ''
        const __fifty = minute ? `<span class="timeline-minute-text">${'50'}</span>` : ''
        const minutes = [
            `<div class="timeline-minute"></div>`,
            `<div class="timeline-minute">${ __ten }</div>`,
            `<div class="timeline-minute"></div>`,
            `<div class="timeline-minute">${ __twenty }</div>`,
            `<div class="timeline-minute"></div>`,
            `<div class="timeline-minute timeline-hour-half">${ __hourHalf }</div>`,
            `<div class="timeline-minute"></div>`,
            `<div class="timeline-minute">${ __forty }</div>`,
            `<div class="timeline-minute"></div>`,
            `<div class="timeline-minute">${ __fifty }</div>`,
            `<div class="timeline-minute"></div>`,
        ]
        minutes.unshift(`<span class="timeline-hour-text">${hour}</span>`)
        return minutes.join('');
    }

    renderTimeline = () => {
        const $timeline = $(this.$timeAxis).find('.time-timeline')
        if (!$timeline.length) return

        console.log(this.#width)
        if (this.#width >= 3600) {
            const hour = new Array(24).fill(null);
            hour.forEach((_, index) => {
                // const idx = (index < 10) ? `0${index}:00` : `${index}:00`;
                let idx = (index < 10) ? `0${index}` : `${index}`;

                const size = this.initMinuteSize(this.#width - 1400);
                const minutes = this.renderMinutes(size, idx, true, true);

                $timeline.append($(`<div class="timeline-hour">${minutes}</div>`));
            }, 0);
        } else if (this.#width >= 1600) {
            const hour = new Array(24).fill(null);
            hour.forEach((_, index) => {
                // const idx = (index < 10) ? `0${index}:00` : `${index}:00`;
                let idx = (index < 10) ? `0${index}` : `${index}`;

                const size = this.initMinuteSize(this.#width - 1400);
                const minutes = this.renderMinutes(size, idx, true);

                $timeline.append($(`<div class="timeline-hour">${minutes}</div>`));
            }, 0);
        } else if (this.#width >= 1000) {
            const hour = new Array(24).fill(null);
            hour.forEach((_, index) => {
                // const idx = (index < 10) ? `0${index}:00` : `${index}:00`;
                const idx = (index < 10) ? `0${index}` : `${index}`;
                const size = this.initMinuteSize(this.#width - 1000);
                const minutes = this.renderMinutes(size, idx);

                console.log('size: => ', size);
                $timeline.append($(`<div class="timeline-hour">${minutes}</div>`));
            });
        } else if (this.#width >= 800) {
            const children = new Array(5).fill({ type: 'minute' });
            children.splice(children.length / 2, children.length % 2, { type: 'hour-half' })
            const hours = createDayHours(24, (item, index) => ({
                ...item,
                children,
                text: (index < 10) ? `0${index}` : `${index}`
            }));
            const timeline = hours.map(this.createTimeline)

            $timeline.html(timeline);
        } else  if (this.#width >= 400) {
            const children = new Array(~~(((this.#width) || 400) / 100)).fill({ type: 'minute' });
            children.splice(children.length / 2, children.length % 2, { type: 'hour-half' })
            const hours = createDayHours(12, (item, index) => ({
                ...item,
                children,
                text: (index * 2 < 10) ? `0${index * 2}` : `${index * 2}`
            }));
            const timeline = hours.map(this.createTimeline)

            $timeline.html(timeline);
        } else {
            const children = new Array(~~((this.#width || 100) / 100)).fill({ type: 'minute' })
            const hours = createDayHours(6, (item, index) => ({
                ...item,
                children,
                text: (index * 4 < 10) ? `0${index * 4}` : `${index * 4}`
            }));
            const timeline = hours.map(this.createTimeline)

            $timeline.html(timeline);
            console.log(hours, timeline)
        }
    }

    createTimeline = ({ type, text = '', children } = {}) => {
        let innerHtml = ''

        if (Array.isArray(children)) innerHtml = children.map(this.createTimeline)?.join('')

        switch (type) {
            case 'hour': {
                return `<div class="timeline-hour"><span class="timeline-hour-text">${text}</span>${ innerHtml }</div>`
            }
            case 'hour-half': {
                return `<div class="timeline-minute timeline-hour-half">${innerHtml}</div>`
            }
            case 'minute': {
                return `<div class="timeline-minute">${innerHtml}</div>`
            }
            default: return ''
        }
    }

    renderScroller = (timelines = [], pointerPositionLeft) => {
        const max = 235959
        const $scroller = $(this.container).find('.time-scroller');
        let ScrollerWidth = $scroller.width();

        scrollMap.length = 0;
        $scroller.find('.time-axis-scroll').remove();
        if (!ScrollerWidth) ScrollerWidth = $(this.container).width();
        timelines.map((item, index) => {
            const [start, end] = WidgetSimple.getIntervalTime(item);
            const width = end - start;
            const __width = ~~((width / max) * 10000) / 100
            const left = ~~(start / max * 10000) / 100
            const startLeft = left / 100 * ScrollerWidth

            scrollMap.push([startLeft, (left + __width) / 100 * ScrollerWidth])
            console.log(start, end, width) // ~~(0.3333333 * 10000) / 100
            $scroller.append(
                $('<div class="time-axis-scroll"/>')
                    .attr('url', item.url)
                    .css('width', `${__width}%`)
                    .css('left', `${left}%`)
            );

            $scroller.css('border-radius', this._option.scroll?.radius);
            if (index === 0) {
                const __left = pointerPositionLeft || `${left}%`;
                const $description = $(this.container).find('.datetime-description');
                const startTime = this.getStartTime(startLeft);

                console.log('startTime: => ', __left, startTime)
                $scroller.find('.time-pointer').css('left', __left);
                $description.css('left', __left);

                if (startTime !== 'Invalid Date') $description.text(startTime);
            }
            // $scroller.append($('<div class="time-axis-scroll"/>').css('width', '50px'));
        });
    }
}